import { useState, useEffect } from 'react';
import {
  Table,
  Row,
  Col,
  Card,
  Pagination,
  Space,
  Modal as AntdModal,
  message,
  Tooltip,
  Button,
  Form,
  InputNumber,
} from 'antd';
import { useRequest, history, useLocation } from 'umi';
import { useToggle, useUpdateEffect } from 'ahooks';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import ColumnBuilder from './builder/ColumnBuilder';
import ActionBuilder from './builder/ActionBuilder';
import SearchBuilder from './builder/SearchBuilder';
import Modal from './component/Modal';
import { submitFieldsAdaptor, exportFile } from './helper';
import styles from './index.less';

const Index = () => {
  const [pageQuery, setPageQuery] = useState({
    per_page: 10,
    page: 1,
    queryfields: '',
  });
  const [sortQuery, setSortQuery] = useState({
    sort: [],
    order: [],
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [modalUri, setModalUri] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [searchVisible, searchAction] = useToggle(false);
  const { confirm } = AntdModal;
  const [searchForm] = Form.useForm();
  const location = useLocation();
  const init = useRequest<{
    data: BasicListApi.ListData;
  }>(
    (values: any) => {
      if (values === true) {
        return {
          method: 'Post',
          url: `${location.pathname.replace('/basic-list', '')}`,
          data: {
            status: true,
            per_page: 10,
            page: 1,
            sort: [],
            order: [],
          },
        };
      }

      return {
        method: 'Post',
        url: `${location.pathname.replace('/basic-list', '')}`,
        data: {
          status: true,
          ...pageQuery,
          ...sortQuery,
        },
      };
    },
    {
      formatResult: (result: any) => result?.data.objectData,
      onSuccess: () => {
        setSelectedRowKeys([]);
        setSelectedRows([]);
      },
    },
  );
  const request = useRequest(
    (values: any) => {
      message.loading({
        content: '请稍候...',
        key: 'process',
        duration: 0,
      });
      const { uri, method, ...formValues } = values;
      return {
        url: `${uri}`,
        method,
        data: formValues,
      };
    },
    {
      manual: true,
      onSuccess: (data: any) => {
        if (data?.data?.success == null || data?.data?.success) {
          message.success({
            content: data?.data?.message,
            key: 'process',
          });
        }
        else {
          message.error({
            content: data?.data?.message,
            key: 'process',
          });
        }
        init.run();
      },
      formatResult: (res: any) => {
        return res;
      },
      throttleInterval: 1000,
    },
  );
  useUpdateEffect(() => {
    init.run();
  }, [pageQuery, sortQuery]);
  useUpdateEffect(() => {
    searchForm.resetFields();
    setPageQuery({
      page: 1,
      per_page: 10,
      queryfields: '',
    });
    setSortQuery({
      sort: [],
      order: [],
    });
  }, [location.pathname]);
  useEffect(() => {
    if (modalUri) {
      setModalVisible(true);
    }
  }, [modalUri]);

  function actionHandler(action: BasicListApi.Action, record: BasicListApi.Field) {
    switch (action.action) {
      case 'modal':
        setModalUri(
          (action.uri || '').replace(/:\w+/g, (field) => {
            return record[field.replace(':', '')];
          }),
        );
        break;

      case 'page': {
        const uri = (action.uri || '').replace(/:\w+/g, (field) => {
          return record[field.replace(':', '')];
        });
        history.push(`/basic-list${uri}`);
        break;
      }

      case 'modelDesign': {
        const uri = (action.uri || '').replace(/:\w+/g, (field) => {
          return record[field.replace(':', '')];
        });
        history.push(`/basic-list/api/models/model-design${uri}`);
        break;
      }

      case 'reportDesign': {
        const uri = (action.uri || '').replace(
          '/api/sql-reports/report-design/:id',
          `/basic-report/api/reports/report-design/${record['id']}`,
        );
        //model desgin /api/sql-reports/report-design/:id
        //final path /basic-report/api/reports/report-design/*
        history.push(uri);
        break;
      }

      case 'reload':
        init.run();
        break;
      case 'exportXls':
        exportFile(
          action.uri || '',
          {
            export: true,
            ...pageQuery,
            ...sortQuery,
          },
          init?.data?.page?.title + '.xlsx',
          {},
        );
        break;
      case 'delete':
      case 'deletePermanently':
      case 'restore': {
        let operationName = '';
        if (action.action.toString() == 'delete') {
          operationName = '删除';
        } else if (action.action.toString() == 'deletePermanently') {
          operationName = '彻底删除';
        } else if (action.action.toString() == 'restore') {
          operationName = '恢复';
        }
        confirm({
          title: `确定【${operationName}】操作`,
          icon: <ExclamationCircleOutlined />,
          content: batchOverview(Object.keys(record).length ? [record] : selectedRows),
          okText: `${operationName}`,
          okType: 'danger',
          cancelText: '取消',

          onOk() {
            return request.run({
              uri: action.uri,
              method: action.method,
              ids: Object.keys(record).length ? [record.id] : selectedRowKeys,
            });
          },
          onCancel() { },
        });
        break;
      }
      case "otherOper":
        {
          const operationName = action.text;
          confirm({
            title: `确定【${operationName}】操作`,
            icon: <ExclamationCircleOutlined />,
            content: batchOverview(Object.keys(record).length ? [record] : selectedRows),
            okText: `${operationName}`,
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              return request.run({
                uri: action.uri,
                method: action.method,
                ids: Object.keys(record).length ? [record.id] : selectedRowKeys,
              });
            },
            onCancel() { },
          });
          break;
        }
      default:
        break;
    }
  }

  function batchOverview(dataSource: BasicListApi.Field[]) {
    const tableColumns = ColumnBuilder(
      init?.data?.layout?.tableColumn,
      actionHandler,
      init?.data?.page?.tableName,
      true
    );
    return (
      <Table
        size="small"
        rowKey="ID"
        columns={[tableColumns[0] || {}, tableColumns[1] || {}]}
        dataSource={dataSource}
        pagination={false}
      />
    );
  }

  const paginationChangeHandler = (page: any, per_page: any) => {
    const tmpPageQuery = { ...pageQuery };
    setPageQuery({
      page: page,
      per_page: per_page,
      queryfields: tmpPageQuery.queryfields,
    });
  };

  const tableChangeHandler = (_: any, __: any, sorter: any) => {
    if (sorter.order === undefined) {
      setSortQuery({
        sort: [],
        order: [],
      });
    } else {
      const orderBy = sorter.order === 'ascend' ? 'asc' : 'desc';
      const tmpsort = [];
      tmpsort.push(sorter.field);
      const tmporderBy = [];
      tmporderBy.push(orderBy);
      setSortQuery({
        sort: tmpsort as any,
        order: tmporderBy as any,
      });
    }
  };

  const hideModal = (reload = false) => {
    setModalVisible(false);
    setModalUri('');

    if (reload) {
      init.run();
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (_selectedRowKeys: any, _selectedRows: any) => {
      setSelectedRowKeys(_selectedRowKeys);
      setSelectedRows(_selectedRows);
    },
  };

  const onFinish = (value: any) => {
    const tmpPageQuery = { ...pageQuery };
    tmpPageQuery.queryfields = JSON.stringify(submitFieldsAdaptor(value));
    setPageQuery(tmpPageQuery);
  };

  const searchLayout = () => {
    return (
      <div style={{ display: searchVisible ? '' : 'none' }}>
        <Card className={styles.searchForm}>
          <Form onFinish={onFinish} form={searchForm}>
            <Row gutter={24}>
              <Col sm={6}>
                <Form.Item label="ID" name="id" key="id">
                  <InputNumber
                    style={{
                      width: '100%',
                    }}
                  />
                </Form.Item>
              </Col>
              {SearchBuilder(init.data?.layout.tableColumn)}
            </Row>
            <Row>
              <Col sm={24} className={styles.textAlignRight}>
                <Space>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    onClick={() => {
                      init.run();
                      searchForm.resetFields();
                      setSelectedRowKeys([]);
                      setSelectedRows([]);
                    }}
                  >
                    重置
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </Card>
      </div>
    );
  };

  const beforeTableLayout = () => {
    return (
      <Row>
        <Col xs={24} sm={24} className={styles.tableToolbar}>
          <Space>
            <Tooltip title="查询">
              <Button
                shape="circle"
                icon={<SearchOutlined />}
                onClick={() => {
                  searchAction.toggle();
                }}
                type={searchVisible ? 'primary' : 'default'}
              />
            </Tooltip>
            {ActionBuilder(init?.data?.layout?.tableToolBar, actionHandler)}
          </Space>
        </Col>
      </Row>
    );
  };

  const afterTableLayout = () => {
    return (
      <Row>
        <Col xs={24} sm={24} className={styles.tableToolbar}>
          <Pagination
            total={init?.data?.meta?.total || 0}
            current={init?.data?.meta?.page || 1}
            pageSize={init?.data?.meta?.perPage || 10}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总共 ${total} 条`}
            onChange={paginationChangeHandler}
            onShowSizeChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  const batchToolbar = () => {
    return (
      selectedRowKeys.length > 0 && (
        <Space>{ActionBuilder(init?.data?.layout?.batchToolBar, actionHandler)}</Space>
      )
    );
  };

  return (
    <PageContainer>
      {searchLayout()}
      <Card>
        {beforeTableLayout()}
        <Table
          rowKey="id"
          dataSource={init?.data?.dataSource}
          columns={ColumnBuilder(
            init?.data?.layout?.tableColumn,
            actionHandler,
            init?.data?.page?.tableName,
            true
          )}
          pagination={false}
          loading={init?.loading}
          onChange={tableChangeHandler}
          rowSelection={rowSelection}
        />
        {afterTableLayout()}
      </Card>
      <Modal modalVisible={modalVisible} hideModal={hideModal} modalUri={modalUri} />
      <FooterToolbar extra={batchToolbar()} />
    </PageContainer>
  );
};

export default Index;
